package org.schueth.tests.buffer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import com.googlecode.ascrblr.api.radio.xspf.AsynchronousBufferedInputStreamWrapper;

public class TestBuffer {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		//File fileorg = new File("/tmp/mistorg");
		//InputStream fin = new FileInputStream(fileorg);
		URL url = new URL("http://www.jotschi.de/mist");
		URLConnection uc = url.openConnection();
		
		File file = new File("/tmp/mist");
		OutputStream fos = new FileOutputStream(file);

		int totalBufferSize =  512* 1024 ;
		AsynchronousBufferedInputStreamWrapper buf = new AsynchronousBufferedInputStreamWrapper(uc.getInputStream(),totalBufferSize);
		buf.startBuffering();
		System.out.println(buf.getBufferLevel());
		Thread.sleep(10);
		System.out.println(buf.getBufferLevel());
		Thread.sleep(100);
		
		copy(buf, fos);

	}

	static void copy(InputStream fis, OutputStream fos) {
		long start = System.currentTimeMillis();
		try {
			byte buffer[] = new byte[1024];
			int nbytes;

			while ((nbytes = fis.read(buffer)) != -1)
			{
				fos.write(buffer, 0, nbytes);
			}
		} catch (IOException e) {
			System.err.println(e);
		} finally {
			if (fis != null)
				try {
					fis.close();
				} catch (IOException e) {
				}

			try {
				if (fos != null)
					fos.close();
			} catch (IOException e) {
			}
		}

		System.out
				.println("copy took: " + (System.currentTimeMillis() - start));
	}

}